import {Engine} from '@designable/core'
import {IFormilySchema, transformToSchema, transformToTreeNode} from '@designable/formily'
import {message} from 'antd'

export const saveSchema = (designer: Engine) => {
    localStorage.setItem(
        'formily-schema',
        JSON.stringify(
            transformToSchema(designer.getCurrentTree(), {
                designableFieldName: 'DesignableField',
                designableFormName: 'Root',
            })
        )
    )
    // message.success('Save Success')
}

export const loadInitialSchema = (designer: Engine) => {
    try {
        const storageStr = localStorage.getItem('formily-schema') || {}
        if (typeof storageStr === "string") {
            designer.setCurrentTree(
                transformToTreeNode(JSON.parse(storageStr), {
                    designableFieldName: 'DesignableField',
                    designableFormName: 'Root',
                })
            )
        }
    } catch {
    }
}

export const getSchema = (designer: Engine):IFormilySchema => {
    return transformToSchema(designer.getCurrentTree(), {
        designableFieldName: 'DesignableField',
        designableFormName: 'Root',
    })
}

export const setSchema = (designer: Engine, jsonSchema: any) => {
    designer.setCurrentTree(
        transformToTreeNode(jsonSchema, {
            designableFieldName: 'DesignableField',
            designableFormName: 'Root',
        })
    )
}
/**
 * 将schema转换为表结构
 * @param schemaJSON
 */
export const schema2Table = (schemaJSON: Record<string, any>) => {
    const table:Record<string, any> = {}
    if(!schemaJSON) return table
    const {schema} = schemaJSON || {}
    const {properties} = schema || {}

    const keys = Object.keys(properties)
    if(!keys.length) return table
    keys.forEach(key => {
        table[key] = ''
    })

    return table
}
